// Copyright (C) 2016 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause

#include <QtWidgets>
#include <QtNetwork>

#include <stdlib.h>

#include "dialog.h"
#include "fortuneserver.h"

Dialog::Dialog(QWidget *parent)
    : QWidget(parent)
{
    statusLabel = new QLabel;
    infoLable= new QLabel;
    statusLabel->setWordWrap(true);
    quitButton = new QPushButton(tr("Quit"));
    quitButton->setAutoDefault(false);


    //如果当前目录下没有唯一的.bin，则退出。
    if(false == find_bin()){
        Dialog::close();
        return;
    }


    //如果TCP Server listen()错误，则退出。
    server= new FortuneServer(this);
    server->set_bin_file(bin_file_name_dlg_path, bin_file_name_dlg);

    if (!server->listen(QHostAddress::Any,54321)) {
        QMessageBox::critical(this, tr("Threaded Fortune Server"),
                              tr("Unable to start the server: %1.")
                              .arg(server->errorString()));
        close();
        return;
    }


    QString ipAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // use the first non-localhost IPv4 address
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            ipAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // if we did not find one, use IPv4 localhost
    if (ipAddress.isEmpty())
        ipAddress = QHostAddress(QHostAddress::LocalHost).toString();

    //TODO这个再看看
    statusLabel->setText(tr("The server is running on                   .\n\nIP: %1\nport: %2\n\n"
                            "use .bin")
                         .arg(ipAddress).arg(server->serverPort()));
    infoLable->setText(tr("---V1.4"));

    connect(quitButton, &QPushButton::clicked, this, &Dialog::close);

    /*在接收者中建立关联：没有运行提示。在发射者中建立关联时，有运行提示。
     * 实测ok。
    */
    //connect(&server, SIGNAL(error(QString)), this, SLOT(show_err(QString)));

    QHBoxLayout *buttonLayout = new QHBoxLayout;
    buttonLayout->addStretch(1);
    buttonLayout->addWidget(quitButton);
    buttonLayout->addStretch(1);

    QVBoxLayout *mainLayout = new QVBoxLayout;
    mainLayout->addWidget(statusLabel);
    mainLayout->addWidget(infoLable);
    mainLayout->addLayout(buttonLayout);
    setLayout(mainLayout);
    setWindowTitle(tr("BinServer"));    //程序窗口标题。
}


/*
*/
bool Dialog::find_bin()
{
    QStringList file_list;

    qDebug()<< QCoreApplication::applicationDirPath();


    QDir binDir(QCoreApplication::applicationDirPath());   //".bin", QDir::Name, QDir::Files. !!已验证，目录"/sdcard/DT45GXX"不存在，目录"/sdcard/DT45G"存在。

    file_list= binDir.entryList({"*.bin"}, QDir::Files, QDir::NoSort);//QDir::AllEntries, QDir::NoSort);  //QDir::Files
    qDebug()<< "files num="<<file_list.size();
    qDebug()<< "files" << file_list;

    if(1 == file_list.size()){
        bin_file_name_dlg_path= QCoreApplication::applicationDirPath()+QString("/");
        bin_file_name_dlg= file_list.value(0);
        qDebug()<< QString("bin_file_name_dlg")<< bin_file_name_dlg_path<< bin_file_name_dlg;
        return true;
    }
    else{
        QMessageBox::warning(this,tr("Error"), tr("在当前目录下没有唯一的.bin"));
        return false;
    }
}

void Dialog::show_err(QString err)
{
    infoLable->setText(err);
}
